package cc.messcat.util;

import cc.messcat.common.security.token.MD5;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.fluent.Request;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.DocumentHelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

public class MessageUtil {

	private static String url;

	private static String account;

	private static String password;

	private static String template;

	public static String sendMessageUtil(String mobile, String content) {

		Properties prop = new Properties();
		InputStream in = MessageUtil.class.getClassLoader().getResourceAsStream("message.properties");
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		try {
			prop.load(br);
			url = prop.getProperty("message.url").trim();
			account = prop.getProperty("message.account").trim();
			password = prop.getProperty("message.password").trim();
//			template = prop.getProperty("message.template").trim();
//			System.out.println(template);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		try {
			return Request.Post(url).bodyForm(new BasicNameValuePair("account", account),
					new BasicNameValuePair("password", MD5.getMD5Code(password)),
					new BasicNameValuePair("mobile", mobile),
					new BasicNameValuePair("content", content))
					.execute().handleResponse(new ResponseHandler<String>() {
						@Override
						public String handleResponse(HttpResponse httpResponse) throws IOException {
							int code=httpResponse.getStatusLine().getStatusCode();
							System.out.println(code);
							if (code!=200){
								return null;
							}
							String result= EntityUtils.toString(httpResponse.getEntity());
							System.out.println(result);
							try {
								return DocumentHelper.parseText(result).getRootElement().elementText("code");
							}catch (Exception e){
								e.printStackTrace();
								return null;
							}
						}
					});
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}
}
